# -*- mode: python ; coding: utf-8 -*-
import os
import sys
import time

# MianWindow.py
# !/usr/bin/env python
# coding=utf-8
from PyQt5.QtCore import QThreadPool, QDateTime, Qt
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QMessageBox

from ui.Ui_main_frame_ui import Ui_MainWindow
from controllers.controller_core import ControllerCore
from hal.hal_serial import HALSerial
'''
sub threads
'''
# from sub_threads.sub_t_monitoring_conn import *
'''
utils
'''
from utils.signals_controller import SignalsController
from utils.global_state import GlobalState
from utils.ui_loader import UILoader
'''
pages
'''
from pages.page_home import PageHome
from pages.page_about import PageAbout




class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.setupUi(self)
        # 设置窗口的固定大小为 1920x1080
        self.setFixedSize(1024, 600)

        self.__init_instance_var()

        self.__restore_settings()

        self.__load_pages_controllers()

        # # 连接各模块信号
        self.signals_controller = SignalsController(self.pages, self.sub_pages_settings, self.controllers)
        self.signals_controller.connect_signals()

        self.__init_all_pages_controllers()

        self.__init_software_state()

    def __restore_settings(self):
        pass

    def __init_all_pages_controllers(self):
        """
        page和controller的init，次序应该是，首先初始化页面，再初始化ctrl
        """
        for page in self.pages.values():
            page.init_page_state()

        # for page in self.sub_pages_settings.values():
        #     page.init_page_state()

        for ctrl in self.controllers.values():
            ctrl.init_ctrl_state()

    def __init_instance_var(self):
        self.__global_state = GlobalState()
        self.__hal_serial = HALSerial()
        self.threadpool = QThreadPool()

        self.t_monitor_conn = None
        # main界面需要被子模块操作的控件，传入子模块
        self.dict_main_widgets = {
            "lb_disp_navi_time": self.lb_disp_navi_time,
            "lb_disp_navi_date": self.lb_disp_navi_date,
        }

    def __load_pages_controllers(self):
        # 初始化主框架下各个页面
        self.pages = {
            "page_home": PageHome(),
            "page_about": PageAbout(),

            # ...
        }
        
        # 加载各模块界面
        self.ui_loader = UILoader(self.stackedWidget)
        self.ui_loader.load_ui(self.pages, 1)

        # 初始化设置页的各个子页面
        self.sub_pages_settings = {
            # "page_settings_e1682": PageE1682(self.threadpool),
            # "page_settings_power": PagePower(),
            # "page_test": PageTest(),
            # ...
        }

        # # 加载各模块界面
        # self.ui_loader = UILoader(self.stacked_w_sys_settings)
        # self.ui_loader.load_ui(self.sub_pages_settings, 0)

        self.controllers = {
            "ctrl_core": ControllerCore(self.threadpool, self.dict_main_widgets),
            # "test": ""
        }

    # @property
    # def page_diagnosis(self):
    #     return self.pages["page_diagnosis"]

    # @property
    # def page_settings_e1682(self):
    #     return self.sub_pages_settings["page_settings_e1682"]

    # @property
    # def page_settings_power(self):
    #     return self.sub_pages_settings["page_settings_power"]

    def __init_software_state(self):
        # 连接页面切换按钮
        # self.pb_stack_e1682.clicked.connect(lambda: self.stacked_w_sys_settings.setCurrentIndex(0))
        # self.pb_stack_power.clicked.connect(lambda: self.stacked_w_sys_settings.setCurrentIndex(1))
        # self.pb_stack_debug.clicked.connect(lambda: self.stacked_w_sys_settings.setCurrentIndex(2))
        self.pb_stackpage_home.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(0))
        self.pb_stackpage_about.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(1))

        # self.pb_stackpage_settings.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(0))
        # self.pb_stackpage_diagnosis.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(1))
        # self.pb_stackpage_dataman.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(2))

        self.pb_quit.clicked.connect(self.closeEvent)

        # 更新navi bar 的时间
        # self.timer_date_label = QTimer(self)
        # self.timer_date_label.timeout.connect(self.__update_time)
        # self.timer_date_label.start(55000)

    def closeEvent(self, event):
        # print(event)
        reply = QMessageBox.question(self, '确认关闭', '确定要关闭程序吗？', QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)

        if reply == QMessageBox.Yes:
            # 关闭线程 t_monitor_conn
            if self.controllers["ctrl_core"].t_monitor_conn is not None and self.controllers["ctrl_core"].t_monitor_conn.is_running:
                self.controllers["ctrl_core"].t_monitor_conn.kill()

            # # 关闭线程 两个采集卡线程
            # if not self.page_settings_e1682.ui.pb_start_e1682.isEnabled():
            #     self.page_settings_e1682.ui.pb_stop_e1682.click()

            # if self.__hal_serial.serial_port_handler is not None:
            #     self.page_settings_power.on_pb_stop_power()

            app = QApplication.instance()
            app.quit()

        else:
            # 如果没有event，则是“退出程序”按钮按下
            if not event:
                return
            # 如果event是true，则是用户点击了右上角关闭按钮
            else:
                event.ignore()



basedir = os.path.dirname(__file__)

try:
    from ctypes import windll  # Only exists on Windows.
    myappid = 'mycompany.myproduct.subproduct.version'
    windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
except ImportError:
    pass


if __name__ == '__main__':
    # bios = wmi.WMI().Win32_BIOS()[0]
    # mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    # mac = hex(uuid.getnode())[2:]
    # for nic in netifaces.interfaces():
    #     iface = netifaces.ifaddresses(nic)[netifaces.AF_LINK]
    #     if len(iface[0]['addr']) > 0:
    #         print("mac address: ", iface[0]['addr'])
    # print("bios", bios.qualifiers['UUID'])
    # print("mac", mac)
    # if bios.qualifiers['UUID'] == "{8502C4E1-5FBB-11D2-AAC1-006008C78BC7}":
    #     print("pc info verify success")

    app = QApplication(sys.argv)

    # print("basedir", basedir)
    # app.setWindowIcon(QIcon(os.path.join(basedir, 'image/icon/logo_snubco.ico')))
    # app.setWindowIcon(QIcon(os.path.join(basedir, 'image/icon/logo_esimtech_blue2.ico')))
    # app.setStyle("Plastique")
    window = MainWindow()
    # 去掉窗口标题栏
    # window.setWindowFlag(Qt.FramelessWindowHint)
    # 窗口最大化
    window.showMaximized()
    # window.showFullScreen()

    app.exec_()